import { MetaMaskSDK } from '@metamask/sdk';
import { Web3 } from 'web3';

export const connectToMetamask = async (errorHandler: (errorMessage?: string) => void) => {
    if (window.ethereum) {
        try {
            // Запрос доступа к MetaMask
            const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }) as  string[];

            // Создание экземпляра web3
            const web3 = new Web3(window.ethereum);

            return {
                account: accounts[0],
                web3,
            };

        } catch (error) {
            errorHandler((error as Error).message);
        }
    } else {
        const MMSDK = new MetaMaskSDK({
            dappMetadata: {
                name: 'Example Pure JS Dapp',
                url: window.location.href,
            },
            injectProvider: true,
        });
        const accounts =  await MMSDK.connect();

        return  {
            account: accounts[0],
        };
    }

};